package com.soup.lab.tools.faker.source;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;

public class FileSourceReaderTestCase {

    private static final Logger logger = LoggerFactory.getLogger(FileSourceReaderTestCase.class);

    @Test
    public void testSmall() {
        SmallFileSourceReader reader = new SmallFileSourceReader(new ClassPathFileSource("a.txt"));
        for (String line : reader) {
            logger.info(line);
        }
    }


    @Test
    public void testBig() {
        BigFileSourceReader reader = new BigFileSourceReader(new ClassPathFileSource("a.txt"), 3);
        for (String line : reader) {
            logger.info(line);
        }
    }

    @Test
    public void testSmallMulti() {
        multiThreadTest(() -> {
            SmallFileSourceReader reader = new SmallFileSourceReader(new ClassPathFileSource("a.txt"));
            for (String line : reader) {
                logger.info(line);
            }
        }, 10);
    }

    @Test
    public void testBigMulti() {
        multiThreadTest(() -> {
            BigFileSourceReader reader = new BigFileSourceReader(new ClassPathFileSource("a.txt"), 3);
            for (String line : reader) {
                logger.info(line);
            }
        }, 10);
    }

    public void multiThreadTest(Runnable runnable, int num) {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch endLatch = new CountDownLatch(num);
        Thread[] threads = new Thread[num];
        for (int i = 0; i < num; i++) {
            threads[i] = new Thread(() -> {
                try {
                    startLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runnable.run();
                endLatch.countDown();
            });
            threads[i].start();
        }
        startLatch.countDown();
        try {
            endLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
